<template>
  <div class="body">
    <!-- 搜索菜单 -->
    <el-form :model="form" label-width="auto" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="活动名称">
            <el-input v-model="form.name" placeholder="请输入活动名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="渠道名称">
            <el-select v-model="form.region1" placeholder="请选择渠道" style="width: 100%">
              <el-option label="ss" value="911" />
              <el-option label="AAAAA五金师傅" value="912" />
              <el-option label="AAAAA师傅跑长途" value="913" />
              <el-option label="AAAAA长途大运" value="914" />
              <el-option label="AAAAA建材批发王哥" value="915" />
              <el-option label="AAAAA红娘牵手赵姐" value="916" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="活动状态">
            <el-select v-model="form.region2" placeholder="请选择活动状态" style="width: 100%">
              <el-option label="正常" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="活动类型">
            <el-select v-model="form.region3" placeholder="请选择活动类型" style="width: 100%">
              <el-option label="折扣卷" value="1" />
              <el-option label="代金卷" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="onSubmit" icon="Search" class="mr-10">搜索</el-button>
            <el-button icon="Refresh" class="mr-10"  @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 功能按钮 -->
    <div class="btn-group">
      <el-button type="primary" plain icon="Plus" @click="openDialog">新增</el-button>
      <el-button type="success" plain :disabled="!selectedRow" icon="Edit" @click="handleEdit">修改</el-button>
      <el-button type="danger" plain :disabled="!selectedRow" icon="Delete" @click="handleDelete">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="tableData" 
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      class="custom-table"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="activityId" label="活动编号"/>
      <el-table-column prop="name" label="活动名称"/>
      <el-table-column prop="channelName" label="渠道名称" />
      <el-table-column prop="info" label="活动简介" />
      <el-table-column prop="type" label="活动类型">
        <template #default="{ row }">
          <span v-if="row.type === 1">
            <el-tag type="primary">折扣卷</el-tag>
          </span>
          <span v-else-if="row.type === 2">
            <el-tag type="success">代金卷</el-tag>
          </span>
          <span v-else>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动明细">
        <template #default="{ row }">
          <span v-if="row.type === 1">折扣卷/{{ row.discount }}折</span>
          <span v-else-if="row.type === 2">代金卷/{{ row.voucher }}元</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="活动状态">
        <template #default="{ row }">
          <span v-if="row.status === 1">
            <el-tag type="primary">正常</el-tag>
          </span>
          <span v-else>
            <el-tag type="info">停用</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="活动起始时间" />
      <el-table-column prop="createTime" label="活动结束时间" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default>
          <el-button link type="primary" size="small" @click="handleEdit">编辑</el-button>
          <el-button link type="primary" size="small" @click="handleDelete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页靠右 -->
    <div class="pagination-right">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <!-- 新增模态框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false" class="custom-dialog">
    <el-form
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="dialog-form"
      ref="dialogFormRef"
    >
      <el-form-item label="渠道来源" prop="region">
        <el-select v-model="ruleForm.region" placeholder="请选择渠道" style="width: 100%">
            <el-option label="ss" value="911" />
            <el-option label="AAAAA五金师傅" value="912" />
            <el-option label="AAAAA师傅跑长途" value="913" />
            <el-option label="AAAAA长途大运" value="914" />
            <el-option label="AAAAA建材批发王哥" value="915" />
            <el-option label="AAAAA红娘牵手赵姐" value="916" />
        </el-select>
      </el-form-item>
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="活动时间" prop="dateRange">
        <el-date-picker
          v-model="ruleForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动简介" prop="desc">
        <el-input v-model="ruleForm.desc" />
      </el-form-item>
      <el-form-item label="活动类型" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择类型" style="width: 100%">
          <el-option label="折扣卷" value="1" />
          <el-option label="代金卷" value="2" />
        </el-select>
      </el-form-item>
      <!-- 只有选中活动类型时才显示计数器，并动态显示label -->
      <el-form-item
        v-if="ruleForm.type"
        :label="ruleForm.type === '1' ? '折扣卷' : (ruleForm.type === '2' ? '代金卷' : '')"
        :prop="ruleForm.type === '1' ? 'discount' : 'voucher'"
      >
        <el-input-number v-model="ruleForm.count" :min="1" :max="100" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSave">确定</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted, reactive, computed } from 'vue'
import Cookies from 'js-cookie'
import dayjs from 'dayjs'

const selectedRow = ref(null)
const isEdit = ref(false) // 新增
const editId = ref(null)  // 新增

const form = reactive({
  name: '',
  region1: '',
  region2: '',
  region3: '',
})

const token = Cookies.get('Admin-Token')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size = ref('default')
const background = ref(false)
const disabled = ref(false)

// 表格数据
const tableData = ref([])

// 新增模态框相关
const dialogVisible = ref(false)

// 只保留五个属性
const ruleForm = reactive({
  name: '',
  region: '',
  dateRange: [], // 新增
  type: '',
  count: 1,
  desc: ''
})

const rules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  region: [{ required: true, message: '请选择渠道来源', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择活动日期', trigger: 'change' }], // 修改
  type: [{ required: true, message: '请选择活动类型', trigger: 'change' }]
}

const dialogTitle = computed(() => isEdit.value ? '修改活动' : '添加活动') // 新增

const openDialog = () => {
  isEdit.value = false
  Object.assign(ruleForm, {
    name: '',
    region: '',
    dateRange: [],
    type: '',
    count: 1,
    desc: ''
  })
  dialogVisible.value = true
}

// 编辑按钮事件
const handleEdit = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要编辑的活动')
    return
  }
  isEdit.value = true
  editId.value = selectedRow.value.activityId
  // 填充表单
  Object.assign(ruleForm, {
    name: selectedRow.value.name,
    region: selectedRow.value.channelId || selectedRow.value.region,
    dateRange: [selectedRow.value.beginTime, selectedRow.value.createTime], // 注意字段名
    type: String(selectedRow.value.type),
    count: selectedRow.value.type === 1 ? selectedRow.value.discount : selectedRow.value.voucher,
    desc: selectedRow.value.info
  })
  dialogVisible.value = true
}

// 搜索参数变量
const searchParams = reactive({
  name: '',
  channelId: '',
  type: '',
  status: ''
})

// 搜索表单与接口参数的映射
const mapFormToParams = () => {
  const params = {}
  if (form.name) params.name = form.name
  if (form.region1) params.channelId = form.region1
  if (form.region3) params.type = form.region3
  if (form.region2) params.status = form.region2
  return params
}

// 获取表格数据，支持传入参数
const fetchTableData = async (params = {}) => {
  try {
    const response = await axios.get(
      'http://47.104.167.34:9100/prod-api/tienchin/activity/list',
      {
        params: {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          ...params
        },
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    tableData.value = response.data.rows || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('请求失败:', error)
  }
}

onMounted(() => {
  fetchTableData()
})
// 搜索
const onSubmit = () => {
  currentPage.value = 1
  const params = mapFormToParams()
  // 只传递分页参数或分页+搜索参数
  fetchTableData(params)
}
// 分页变化时也带上搜索参数
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTableData(mapFormToParams())
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData(mapFormToParams())
}
const handleSelectionChange = (selection) => {
  selectedRow.value = selection.length > 0 ? selection[0] : null
}
const selectable = (row, index) => true
const handleClick = () => {
  console.log('detail clicked')
}

const dialogFormRef = ref(null)

// 保存
const handleSave = async () => {
  dialogFormRef.value.validate(async (valid) => {
    if (!valid) return
    const [begin, end] = ruleForm.dateRange || []
    const beginTime = begin ? dayjs(begin).format('YYYY-MM-DD HH:mm:ss') : ''
    const endTime = end ? dayjs(end).format('YYYY-MM-DD HH:mm:ss') : ''
    const newForm = {
      name: ruleForm.name,
      channelId: ruleForm.region,
      type: Number(ruleForm.type),
      info: ruleForm.desc,
      beginTime,
      endTime,
      activityTime: [beginTime, endTime],
      discount: ruleForm.type === '1' ? ruleForm.count : undefined,
      voucher: ruleForm.type === '2' ? ruleForm.count : undefined
    }
    try {
      if (isEdit.value) {
        // 编辑
        await axios.put(`http://47.104.167.34:9100/prod-api/tienchin/activity`, {
          ...newForm,
          activityId: editId.value
        }, {
          headers: { Authorization: `Bearer ${token}` }
        })
        ElMessage.success('修改成功')
      } else {
        // 新增
        await axios.post('http://47.104.167.34:9100/prod-api/tienchin/activity',
          newForm,
          { headers: { Authorization: `Bearer ${token}` } }
        )
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchTableData()
    } catch (error) {
      ElMessage.error(isEdit.value ? '修改失败' : '新增失败')
      console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
    }
  })
}

const handleDelete = async () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要删除的活动')
    return
  }
  try {
    await ElMessageBox.confirm(
      `是否确认删除活动编号为 "${selectedRow.value.activityId}" 的数据项？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await axios.delete(`http://47.104.167.34:9100/prod-api/tienchin/activity/${selectedRow.value.activityId}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    ElMessage.success('删除成功')
    fetchTableData()
    selectedRow.value = null
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
    // 用户取消时不提示
  }
}

const handleExport = async () => {
  try {
    const response = await axios.post(
      'http://47.104.167.34:9100/prod-api/tienchin/activity/export',
      {
        pageNum: 1,
        pageSize: 10,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`
        },
        responseType: 'blob' // 关键：以二进制流接收
      }
    )
    // 创建blob对象
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    // 文件名可自定义
    link.download = `活动列表_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
    console.error('导出失败:', error)
  }
}

const handleReset = () => {
  form.name = ''
  form.region1 = ''
  form.region2 = ''
  form.region3 = ''
}


</script>

<style lang="scss" scoped>
.body{
  padding: 20px;
  background: #f8f9fb;
  min-height: 100vh;
}
.search-form {
  background: #fff;
  padding: 24px 24px 8px 24px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin-bottom: 20px;
}
.btn-group {
  margin-bottom: 16px;
  .el-button {
    margin-right: 10px;
  }
}
.custom-table {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin-bottom: 20px;
}
.pagination-right {
  margin-top: 16px;
  text-align: right;
}
.custom-dialog .el-dialog__body {
  padding: 24px 32px 8px 32px;
  background: #f8f9fb;
}
.dialog-form {
  background: #fff;
  padding: 16px 24px 0 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
</style>